package com.blockmeta.bbs.immodule.widget;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;

import com.blockmeta.bbs.baselibrary.base.adapter.BaseAdapter;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.utils.DimentionsUtil;
import com.blockmeta.bbs.immodule.bean.beaninterface.ICircleEntry;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

/**
 * @author AirThor
 * @date 2019/3/5.
 * IM 联系人加入的圈子列表装饰器 在每组的第一个item上方绘制Letter 其它的绘制分割线
 */
public class CircleItemDecoration extends RecyclerView.ItemDecoration {
    private static final int mLetterHeight = DimentionsUtil.dp2px(BaseApp.getApp(),36f);
    private static final int DP_68 = DimentionsUtil.dp2px(BaseApp.getApp(),68f);
    private static final int DP_100 = DimentionsUtil.dp2px(BaseApp.getApp(),100f);
    private static final int DP_14 = DimentionsUtil.dp2px(BaseApp.getApp(),14f);
    private static final int DP_1 = DimentionsUtil.dp2px(BaseApp.getApp(),1f);

    private List<ICircleEntry> mEntries;

    private int mSectionIndices = -1;

    private Paint mDividerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Paint mLetterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private int mDividerMargin = DP_68;

    private BaseAdapter<ICircleEntry, BaseViewHolder> mBaseAdapter;
    /**
     * 是否支持分组 默认支持
     */
    private boolean mSupportGroup = true;

    public void setSupportGroup(boolean supportGroup) {
        mSupportGroup = supportGroup;
    }

    /**
     * 处于编辑模式时 分割线要更短
     * @param editMode 是否编辑模式
     */
    public void setEditable(boolean editMode) {
        mDividerMargin = editMode?DP_100:DP_68;
    }

    public CircleItemDecoration(BaseAdapter<ICircleEntry, BaseViewHolder> adapter) {
        mBaseAdapter = adapter;
        adapter.registerAdapterDataObserver(new DataObserver());
        mEntries = adapter.getData();

        mDividerPaint.setColor(Color.parseColor("#F8F8F8"));
        mDividerPaint.setStrokeWidth(DP_1);

        mLetterPaint.setColor(Color.BLACK);
        mLetterPaint.setTextSize(DP_14);
        mLetterPaint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));

        if (mSupportGroup) {
            mSectionIndices = getSectionIndices();
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildLayoutPosition(view);
        int headerCount = mBaseAdapter.getHeaderLayoutCount();
        int dataPosition = position-headerCount;
        boolean isHeaderView = mBaseAdapter.getItemViewType(position)== BaseQuickAdapter.HEADER_VIEW;
        if (!isHeaderView&&mSectionIndices==dataPosition&&mSectionIndices!=-1){
            outRect.top = mLetterHeight;
        }else if (!isHeaderView&&dataPosition!=0){
            outRect.top = DP_1;
        }
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (!(layoutManager instanceof LinearLayoutManager)){return;}
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            int position = parent.getChildLayoutPosition(child);
            int dataPosition = position-mBaseAdapter.getHeaderLayoutCount();
            boolean isHeaderView = mBaseAdapter.getItemViewType(position)== BaseQuickAdapter.HEADER_VIEW;
            if (!isHeaderView&&mSectionIndices==dataPosition&&mSectionIndices!=-1){
                drawLetter(c,child);
            }else if (!isHeaderView&&mSectionIndices!=0){
                drawLine(c,child);
            }
        }
    }

    private void drawLine(Canvas c, View child) {
        float left = mDividerMargin;
        float y = child.getTop()-DP_1/2f;
        float right = child.getRight();
        c.drawLine(left,y,right,y,mDividerPaint);
    }

    private void drawLetter(Canvas c, View child) {
        float left = child.getLeft();
        float top = child.getTop()-mLetterHeight;
        float right = child.getRight();
        float bottom =child.getTop();
        c.drawRect(left,top,right,bottom,mDividerPaint);
        float y =(bottom-top-mLetterPaint.getFontMetrics().descent+mLetterPaint.getFontMetrics().ascent)/2-mLetterPaint.getFontMetrics().ascent;
        c.drawText("热门圈子",DP_14,top+y,mLetterPaint);
    }

    /**
     * 获取每个部分的第一个的位置存在一个数组里
     * @return 每个部分的index
     */
    private int getSectionIndices() {
        if (mEntries.size() > 0) {
            for (int i = 0; i < mEntries.size(); i++) {
                if (mEntries.get(i).recommendCircle()) {
                    return i;
                }
            }
        }
        return -1;
    }


    class DataObserver extends RecyclerView.AdapterDataObserver{
        public DataObserver() {

        }

        @Override
        public void onChanged() {
            updateData();
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            updateData();
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
            updateData();
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            updateData();
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            updateData();
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
            updateData();
        }
    }

    private void updateData(){
        mEntries = mBaseAdapter.getData();
        if (mSupportGroup) {
            mSectionIndices = getSectionIndices();
        }
    }
}
